// API配置界面增强功能

// 初始化API配置界面功能
function initApiConfigFeatures() {
    // 添加眼睛图标切换功能
    document.addEventListener('click', function(e) {
        if (e.target.closest('.toggle-visibility')) {
            const button = e.target.closest('.toggle-visibility');
            const targetId = button.getAttribute('data-target');
            const input = document.getElementById(targetId);
            const eyeIcon = button.querySelector('.eye-icon');
            
            if (input) {
                if (input.type === 'password') {
                    input.type = 'text';
                    eyeIcon.textContent = '🙈';
                } else {
                    input.type = 'password';
                    eyeIcon.textContent = '👁️';
                }
            }
        }
    });
    
    // 添加单个配置保存功能
    document.addEventListener('click', function(e) {
        if (e.target.classList.contains('btn-save-single')) {
            const provider = e.target.getAttribute('data-provider');
            saveSingleApiConfig(provider);
        }
    });
}

// 保存单个API配置
async function saveSingleApiConfig(provider) {
    console.log('保存单个配置:', provider);
    
    const button = document.querySelector(`[data-provider="${provider}"]`);
    if (button) {
        button.disabled = true;
        button.textContent = '保存中...';
    }
    
    try {
        let config = null;
        
        switch (provider) {
            case 'deepseek':
                const deepseekKey = document.getElementById('deepseekApiKey').value.trim();
                if (!deepseekKey) {
                    showMessage('请输入DeepSeek API密钥', 'error');
                    return;
                }
                config = {
                    name: 'DeepSeek AI服务',
                    provider: 'deepseek',
                    api_key: deepseekKey,
                    notes: 'ET项目DeepSeek AI对话服务',
                    api_config: {
                        model: document.getElementById('deepseekModel').value
                    }
                };
                break;
                
            case 'volcengine':
                const volcengineKey = document.getElementById('volcengineImageKey').value.trim();
                if (!volcengineKey) {
                    showMessage('请输入火山引擎API密钥', 'error');
                    return;
                }
                config = {
                    name: '火山引擎图片生成服务',
                    provider: 'volcengine',
                    api_key: volcengineKey,
                    notes: 'ET项目火山引擎图片生成服务',
                    api_config: {
                        model: document.getElementById('volcengineImageModel').value
                    }
                };
                break;
                
            case 'volcengine_tts':
                const ttsAppId = document.getElementById('volcengineTtsAppId').value.trim();
                const ttsAccessToken = document.getElementById('volcengineTtsAccessToken').value.trim();
                if (!ttsAppId || !ttsAccessToken) {
                    showMessage('请输入完整的TTS配置信息', 'error');
                    return;
                }
                config = {
                    name: '火山引擎语音合成服务',
                    provider: 'volcengine_tts',
                    api_key: ttsAccessToken,
                    notes: 'ET项目火山引擎TTS服务',
                    api_config: {
                        appId: ttsAppId,
                        cluster: document.getElementById('volcengineTtsCluster').value,
                        resourceId: document.getElementById('volcengineTtsResourceId').value,
                        voiceType: document.getElementById('volcengineTtsVoice').value,
                        secretKey: document.getElementById('volcengineTtsSecretKey').value.trim()
                    }
                };
                break;
                
            case 'openai':
                const openaiKey = document.getElementById('openaiApiKey').value.trim();
                if (!openaiKey) {
                    showMessage('请输入OpenAI API密钥', 'error');
                    return;
                }
                config = {
                    name: 'OpenAI服务',
                    provider: 'openai',
                    api_key: openaiKey,
                    notes: 'OpenAI API服务'
                };
                break;
                
            case 'claude':
                const claudeKey = document.getElementById('claudeApiKey').value.trim();
                if (!claudeKey) {
                    showMessage('请输入Claude API密钥', 'error');
                    return;
                }
                config = {
                    name: 'Claude服务',
                    provider: 'claude',
                    api_key: claudeKey,
                    notes: 'Anthropic Claude API服务'
                };
                break;
                
            case 'gemini':
                const geminiKey = document.getElementById('geminiApiKey').value.trim();
                if (!geminiKey) {
                    showMessage('请输入Gemini API密钥', 'error');
                    return;
                }
                config = {
                    name: 'Gemini服务',
                    provider: 'gemini',
                    api_key: geminiKey,
                    notes: 'Google Gemini API服务'
                };
                break;
                
            default:
                showMessage('未知的配置类型', 'error');
                return;
        }
        
        if (config) {
            const result = await fetchAPI('/api/api-keys', 'POST', config);
            
            if (result && result.success) {
                showMessage(`${config.name}配置保存成功`, 'success');
                // 重新加载配置状态
                await loadApiConfig();
            } else {
                showMessage(`保存失败: ${result?.error || '未知错误'}`, 'error');
            }
        }
        
    } catch (error) {
        console.error('保存单个配置失败:', error);
        showMessage('保存配置时发生错误', 'error');
    } finally {
        if (button) {
            button.disabled = false;
            button.textContent = `保存${getProviderDisplayName(provider)}配置`;
        }
    }
}

// 获取提供商显示名称
function getProviderDisplayName(provider) {
    const names = {
        'deepseek': 'DeepSeek',
        'volcengine': '图片生成',
        'volcengine_tts': 'TTS',
        'openai': 'OpenAI',
        'claude': 'Claude',
        'gemini': 'Gemini'
    };
    return names[provider] || provider;
}